package com.have.blog.xo.service.admin.impl;

import com.github.pagehelper.PageHelper;
import com.have.blog.base.enums.BlogStatus;
import com.have.blog.base.holder.RequestHolder;
import com.have.blog.commons.config.jwt.Audience;
import com.have.blog.model.api.CommonPage;
import com.have.blog.model.mapper.TSysDictDataMapper;
import com.have.blog.model.mapper.TSysDictTypeMapper;
import com.have.blog.model.models.TBlog;
import com.have.blog.model.models.TSysDictDataExample;
import com.have.blog.model.models.TSysDictType;
import com.have.blog.model.models.TSysDictTypeExample;
import com.have.blog.utils.MyStringUtils;
import com.have.blog.utils.ResultUtils;
import com.have.blog.xo.constant.MessageConstant;
import com.have.blog.xo.constant.SysConstant;
import com.have.blog.xo.service.admin.SystemDictTypeService;
import com.have.blog.xo.vo.SystemDictTypeVo;
import com.have.haveblog.security.utils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Service
@SuppressWarnings("all")
public class SystemDictTypeServiceImpl implements SystemDictTypeService {
    @Autowired
    private TSysDictTypeMapper dictTypeMapper;
    @Autowired
    private TSysDictDataMapper dictDataMapper;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private Audience audience;

    @Override
    public String getPageList(SystemDictTypeVo sysDictTypeVO) {
        PageHelper.startPage(sysDictTypeVO.getCurrentPage(), sysDictTypeVO.getPageSize());

        TSysDictTypeExample example = new TSysDictTypeExample();
        TSysDictTypeExample.Criteria criteria = example.createCriteria();
        // 字典名称
        if (!StringUtils.isEmpty(sysDictTypeVO.getDictName()) && !StringUtils.isEmpty(sysDictTypeVO.getDictName().trim())) {
            criteria.andDictNameLike("%" + sysDictTypeVO.getKeyword() + "%");
        }
        // 字典类型
        if (!StringUtils.isEmpty(sysDictTypeVO.getDictType()) && !StringUtils.isEmpty(sysDictTypeVO.getDictType().trim())) {
            criteria.andDictTypeEqualTo(sysDictTypeVO.getDictType().trim());
        }
        if (!StringUtils.isEmpty(sysDictTypeVO.getOrderByAscColumn())) {
            String column = MyStringUtils.underLine(new StringBuffer(sysDictTypeVO.getOrderByAscColumn())).toString();
            example.setOrderByClause(column + " asc");
        } else if (!StringUtils.isEmpty(sysDictTypeVO.getOrderByDescColumn())) {
            // 将驼峰转换成下划线
            String column = MyStringUtils.underLine(new StringBuffer(sysDictTypeVO.getOrderByDescColumn())).toString();
            example.setOrderByClause(column + " desc");
        } else {
            example.setOrderByClause("sort,create_time desc");
        }
        criteria.andStatusEqualTo(BlogStatus.ENABLE.getStatus());
        List<TSysDictType> sysDictTypeList = dictTypeMapper.selectByExample(example);
        return ResultUtils.successWithData(CommonPage.restPage(sysDictTypeList));
    }

    @Override
    public String addSysDictType(SystemDictTypeVo sysDictTypeVO) {
        HttpServletRequest request = RequestHolder.getRequest();
        String token = request.getAttribute(SysConstant.TOKEN).toString();
        String adminUid = jwtTokenUtil.getAdminUid(token, audience.getBase64Secret());
        TSysDictTypeExample example = new TSysDictTypeExample();
        example.createCriteria()
                .andStatusEqualTo(BlogStatus.ENABLE.getStatus())
                .andDictTypeEqualTo(sysDictTypeVO.getDictType());
        long count = dictTypeMapper.countByExample(example);
        if (count > 0) {
            return ResultUtils.successWithData(MessageConstant.ENTITY_EXIST);
        }
        TSysDictType tSysDictType = new TSysDictType();
        tSysDictType.setUid(MyStringUtils.getUUID());
        tSysDictType.setDictName(sysDictTypeVO.getDictName());
        tSysDictType.setDictType(sysDictTypeVO.getDictType());
        tSysDictType.setRemark(sysDictTypeVO.getRemark());
        tSysDictType.setIsPublish(sysDictTypeVO.getIsPublish());
        tSysDictType.setSort(sysDictTypeVO.getSort());
        tSysDictType.setStatus(BlogStatus.ENABLE.getStatus());
        tSysDictType.setCreateByUid(adminUid);
        tSysDictType.setUpdateByUid(adminUid);
        tSysDictType.setCreateTime(new Date());
        tSysDictType.setUpdateTime(new Date());
        int result = dictTypeMapper.insert(tSysDictType);
        if (result > 0) {
            return ResultUtils.successWithMessage(MessageConstant.INSERT_SUCCESS);
        }
        return ResultUtils.errorWithMessage(MessageConstant.INSERT_FAIL);
    }

    @Override
    public String editSysDictType(SystemDictTypeVo sysDictTypeVO) {
        HttpServletRequest request = RequestHolder.getRequest();
        String token = request.getAttribute(SysConstant.TOKEN).toString();
        String adminUid = jwtTokenUtil.getAdminUid(token, audience.getBase64Secret());

        TSysDictType sysDictType = dictTypeMapper.selectByPrimaryKey(sysDictTypeVO.getUid());
        if (!sysDictType.getDictType().equals(sysDictTypeVO.getDictType())) {
            TSysDictTypeExample example = new TSysDictTypeExample();
            example.createCriteria()
                    .andStatusEqualTo(BlogStatus.ENABLE.getStatus())
                    .andDictTypeEqualTo(sysDictTypeVO.getDictType());
            long count = dictTypeMapper.countByExample(example);
            if (count > 0) {
                return ResultUtils.errorWithMessage(MessageConstant.ENTITY_EXIST);
            }
        }

        sysDictType.setDictType(sysDictTypeVO.getDictType());
        sysDictType.setDictName(sysDictTypeVO.getDictName());
        sysDictType.setRemark(sysDictTypeVO.getRemark());
        sysDictType.setIsPublish(sysDictTypeVO.getIsPublish());
        sysDictType.setSort(sysDictTypeVO.getSort());
        sysDictType.setUpdateByUid(adminUid);
        sysDictType.setUpdateTime(new Date());
        int result = dictTypeMapper.updateByPrimaryKeySelective(sysDictType);
        // TODO redis相关操作
        if (result > 0) {
            return ResultUtils.successWithMessage(MessageConstant.UPDATE_SUCCESS);
        }
        return ResultUtils.errorWithMessage(MessageConstant.UPDATE_FAIL);
    }

    @Override
    public String deleteBatchSysDictType(List<SystemDictTypeVo> sysDictTypeVoList) {
        HttpServletRequest request = RequestHolder.getRequest();
        String token = request.getAttribute(SysConstant.TOKEN).toString();
        String adminUid = jwtTokenUtil.getAdminUid(token, audience.getBase64Secret());

        if (CollectionUtils.isEmpty(sysDictTypeVoList)) {
            return ResultUtils.errorWithMessage(MessageConstant.PARAM_INCORRECT);
        }
        List<String> uids = new ArrayList<>();
        sysDictTypeVoList.forEach(item -> {
            uids.add(item.getUid());
        });

        // 判断要删除的分类，是否有博客
        TSysDictDataExample example = new TSysDictDataExample();
        example.createCriteria()
                .andStatusEqualTo(BlogStatus.ENABLE.getStatus())
                .andDictTypeUidIn(uids);

        long count = dictDataMapper.countByExample(example);
        if (count > 0) {
            return ResultUtils.errorWithMessage(MessageConstant.DICT_DATA_UNDER_THIS_SORT);
        }

        TSysDictTypeExample typeExample = new TSysDictTypeExample();
        typeExample.createCriteria()
                .andUidIn(uids)
                .andStatusEqualTo(BlogStatus.ENABLE.getStatus());
        TSysDictType template = new TSysDictType();
        template.setStatus(BlogStatus.DISABLE.getStatus());
        int result = dictTypeMapper.updateByExampleSelective(template, typeExample);

        if (result > 0) {
            return ResultUtils.successWithMessage(MessageConstant.DELETE_SUCCESS);
        } else {
            return ResultUtils.errorWithMessage(MessageConstant.DELETE_FAIL);
        }
    }
}
